import { useState, useEffect } from "react";
import QRCode from "react-qr-code";
import axios from "axios";

function App() {
  const [env, setEnv] = useState("浏览器");
  const [config, setConfig] = useState({
    renameFiles: true,
    overwriteExisting: true,
    storagePath: "uploads",
  });
  const [ip, setIp] = useState("");
  const [selectedFiles, setSelectedFiles] = useState<FileList | null>(null);
  const [fileProgress, setFileProgress] = useState<Record<string, number>>({});
  const [isUploading, setIsUploading] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [uploadStatus, setUploadStatus] = useState<string>("");
  const [configSaveStatus, setConfigSaveStatus] = useState<string>("");

  const handleRefresh = () => {
    setIsRefreshing(true);
    setSelectedFiles(null);
    setFileProgress({});

    console.log(
      "发起IP请求:",
      `http://${window.location.hostname}:3001/ip`,
      "时间戳:",
      Date.now()
    );
    axios
      .get(`http://${window.location.hostname || "localhost"}:3001/ip`)
      .then((res) => setIp(res.data.ip))
      .catch(console.error)
      .finally(() => setIsRefreshing(false));
  };

  useEffect(() => {
    // 环境检测逻辑
    const isElectron = /Electron\/\d+\.\d+\.\d+/.test(navigator.userAgent);
    if (isElectron) {
      setEnv("Electron");
      window.electronAPI.readConfig()
        .then((config) => {
          setConfig(config);
          return window.electronAPI.saveConfig(config);
        })
        .then(() => {
          setConfigSaveStatus("success");
          setTimeout(() => setConfigSaveStatus(""), 2000);
        })
        .catch((error) => {
          console.error("配置保存失败:", error);
          setConfigSaveStatus("error");
          setTimeout(() => setConfigSaveStatus(""), 2000);
        });
    }
    handleRefresh();
  }, []);

  const handleUpload = async () => {
    if (!selectedFiles || isUploading) return;
    setIsUploading(true);

    const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB分块
    const CONCURRENT_LIMIT = 6; // 并发数量

    try {
      await Promise.all(
        Array.from(selectedFiles).map(async (file) => {
          const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
          const uploadQueue = [];

          // 创建分块上传任务
          for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
            const start = chunkIndex * CHUNK_SIZE;
            const end = Math.min(start + CHUNK_SIZE, file.size);
            const chunk = file.slice(start, end);

            uploadQueue.push({
              chunkIndex,
              formData: (() => {
                const fd = new FormData();
                fd.append('chunk', chunk);
                fd.append('fileName', file.name);
                fd.append('chunkIndex', String(chunkIndex));
                fd.append('totalChunks', String(totalChunks));
                return fd;
              })()
            });
          }

          // 分块并发上传
          const uploadPromises = [];
          const activeUploads = new Set();

          while (uploadQueue.length > 0) {
            while (activeUploads.size < CONCURRENT_LIMIT && uploadQueue.length > 0) {
              const { chunkIndex, formData } = uploadQueue.shift();
              // 如果 formData 是空的，跳过这个任务
              if (!formData) {
                console.warn(`Skipping empty formData for chunk ${chunkIndex}`);
                console.log("formData:", formData);
                continue;
              };
              const promise = axios.post(`http://${window.location.hostname || ip}:3001/upload-chunk`, formData, {
                headers: {
                  'Content-Type': 'multipart/form-data'
                }
              }).then(response => {
                const receivedChunks = response.data.received?.length || 0;
                setFileProgress(prev => ({
                  ...prev,
                  [file.name]: Math.min(
                    (receivedChunks / totalChunks) * 100,
                    99.9
                  )
                }));
              }).finally(() => activeUploads.delete(promise));

              activeUploads.add(promise);
              uploadPromises.push(promise);
            }
            await Promise.race(activeUploads);
          }
          await Promise.all(uploadPromises);

          // 强制设置最终进度为100%
          setFileProgress(prev => ({
            ...prev,
            [file.name]: 100
          }));
        })
      );
      setUploadStatus('success');
    } catch (err) {
      console.error("上传错误详情:", {
        error: err,
        response: {
          status: err.response?.status,
          data: err.response?.data,
          headers: err.response?.headers,
        },
        request: {
          method: err.config?.method,
          url: err.config?.url,
          data: err.config?.data,
        },
      });
      const errorType = err.response?.data?.errorType;
      const errorMessage = err.response?.data?.message || err.message;

      alert(
        `上传失败: ${JSON.stringify(
          {
            错误类型: errorType,
            错误信息: errorMessage,
            状态码: err.response?.status,
            请求路径: err.config?.url,
          },
          null,
          2
        )}`
      );
      console.error("完整错误对象:", err);
      console.error("错误类型:", errorType);
    } finally {
      setIsUploading(false);
      setSelectedFiles(null);
      setFileProgress({});
    }
  };

  return (
    <div style={{ padding: 20 }}>
      <div
        style={{
          padding: "8px 16px",
          background: env === "Electron" ? "#4CAF50" : "#2196F3",
          color: "white",
          borderRadius: 4,
          marginBottom: 20,
        }}
      >
        当前运行环境：{env}
      </div>
      {env === "Electron" && (
        <div
          style={{
            marginBottom: 20,
            padding: 15,
            background: "#f5f5f5",
            borderRadius: 8,
          }}
        >
          <h3>传输配置</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <label>
              <input
                type="checkbox"
                checked={config.renameFiles}
                onChange={(e) =>
                  setConfig({ ...config, renameFiles: e.target.checked })
                }
              />
              自动重命名文件
            </label>

            <label>
              <input
                type="checkbox"
                checked={config.overwriteExisting}
                onChange={(e) =>
                  setConfig({ ...config, overwriteExisting: e.target.checked })
                }
              />
              覆盖已存在文件
            </label>

            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <span>存储路径：</span>
              <input
                type="text"
                value={config.storagePath}
                onChange={(e) =>
                  setConfig({ ...config, storagePath: e.target.value })
                }
                style={{ flex: 1, padding: 6 }}
              />
            </div>

            <button
              onClick={() =>
                window.electronAPI
                  .saveConfig(config)
                  .then(() => {
                    setConfigSaveStatus("success");
                    setTimeout(() => setConfigSaveStatus(""), 2000);
                  })
                  .catch((error) => {
                    console.error("配置保存失败:", error);
                    setConfigSaveStatus("error");
                    setTimeout(() => setConfigSaveStatus(""), 2000);
                  })
              }
              style={{
                background: "#4CAF50",
                color: "white",
                padding: "8px 16px",
                border: "none",
                borderRadius: 4,
                cursor: "pointer",
              }}
            >
              保存配置
            </button>
            {configSaveStatus === "success" && (
              <div style={{ color: "#4CAF50", marginLeft: 10 }}>
                ✓ 配置保存成功
              </div>
            )}
            {configSaveStatus === "error" && (
              <div style={{ color: "#f44336", marginLeft: 10 }}>
                ✗ 配置保存失败
              </div>
            )}
          </div>
        </div>
      )}
      <h1>局域网文件传输</h1>
      <div style={{ marginBottom: 30, background: "white", padding: 15 }}>
        <QRCode value={`http://${ip}:3000`} size={256} level="H" />
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          {ip ? (
            <p>扫描二维码连接: {ip}</p>
          ) : (
            <div
              style={{
                color: "#f44336",
                padding: "4px 8px",
                background: "#ffe6e6",
                borderRadius: 4,
              }}
            >
              请点击刷新重试
            </div>
          )}
          <button
            onClick={handleRefresh}
            disabled={isRefreshing}
            style={{
              background: isRefreshing
                ? "linear-gradient(135deg, #b3e5fc, #81d4fa)"
                : "linear-gradient(135deg, #2196F3, #1976D2)",
              color: "white",
              padding: "6px 12px",
              border: "none",
              borderRadius: "20px",
              cursor: isRefreshing ? "wait" : "pointer",
              transition: "all 0.3s ease",
              display: "flex",
              alignItems: "center",
              gap: 6,
            }}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" />
            </svg>
            {isRefreshing ? "刷新中..." : "刷新"}
          </button>
        </div>
      </div>
      <input
        type="file"
        multiple
        style={{
          margin: "10px 0",
          padding: "12px",
          border: "2px solid #2196F3",
          borderRadius: "8px",
          width: "300px",
        }}
        onChange={(e) => setSelectedFiles(e.target.files)}
      />
      {selectedFiles?.length && <p>已选择 {selectedFiles.length} 个文件</p>}
      <button
        onClick={handleUpload}
        disabled={isUploading}
        style={{
          background: isUploading
            ? "linear-gradient(135deg, #b3e5fc, #81d4fa)"
            : "linear-gradient(135deg, #2196F3, #1976D2)",
          color: "white",
          padding: "12px 24px",
          border: "none",
          borderRadius: "8px",
          cursor: isUploading ? "wait" : "pointer",
          transition: "all 0.3s ease",
          boxShadow: "0 4px 6px rgba(0, 0, 0, 0.1)",
          ":hover": {
            boxShadow: "0 6px 8px rgba(0, 0, 0, 0.2)",
            transform: "translateY(-2px)",
          },
          ":active": {
            transform: "translateY(0)",
            boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
          },
        }}
      >
        {isUploading ? "上传中..." : "开始传输"}
      </button>
      {Array.from(selectedFiles || []).map((file) => (
        <div key={file.name} style={{ margin: "8px 0" }}>
          <div style={{ display: "flex", alignItems: "center" }}>
            <span style={{ width: 120 }}>{file.name}</span>
            <progress
              value={fileProgress[file.name] || 0}
              max="100"
              style={{
                width: 200,
                height: 12,
                borderRadius: 6,
                overflow: "hidden",
              }}
            />
            <span style={{ marginLeft: 10, minWidth: 40 }}>
              {(fileProgress[file.name] || 0).toFixed(3)}%
            </span>
          </div>
        </div>
      ))}
      {uploadStatus === "success" && (
        <div style={{ color: "#4CAF50", marginLeft: 10 }}>✓ 上传成功</div>
      )}
      {uploadStatus === "error" && (
        <div style={{ color: "#f44336", marginLeft: 10 }}>✗ 上传失败</div>
      )}
    </div>
  );
}

export default App;
